import 'package:get/get.dart';
import 'package:kkhousekeep/config/constant.dart';
import 'package:kkhousekeep/models/member_list_entity.dart';
import 'package:kkhousekeep/net/me_connect.dart';
import 'package:kkhousekeep/net/me_member_connect.dart';
import 'package:kkhousekeep/page/login/login_controller.dart';
import 'package:kkhousekeep/page/me/my_house.dart';
import 'package:kkhousekeep/page/me/setting.dart';
import 'package:kkhousekeep/tools/shared_preferences.dart';

import '../../net/home_connect.dart';
import 'family_member.dart';

class MeController extends GetxController {
  var userType = UserType.owner.obs;

  var name = "".obs;

  var description = "".obs;

  var hasNewMsg = false.obs;

  late HomeConnect _homeConnect;
  late MeConnect _meConnect;

  @override
  void onInit() {
    super.onInit();
    if (!Get.isRegistered<HomeConnect>()) {
      _homeConnect = Get.put(HomeConnect());
    } else {
      _homeConnect = Get.find<HomeConnect>();
    }
    _meConnect = Get.put(MeConnect());
    loadSpData();
  }

  Future<void> loadSpData() async {
    userType.value = await getSp().getUserType();
    if (userType.value == UserType.property) {
      name.value = await getSp().getUserName();
      description.value = await getSp().getRelation();
    } else {
      var meMemberConnect = Get.isRegistered<MeMemberConnect>()
          ? Get.find<MeMemberConnect>()
          : Get.put(MeMemberConnect());
      var meMemberList = await meMemberConnect.getMemberList();
      var roomInfo = await _homeConnect.getRoomInfo();
      name.value = await getSp().getOwnerName();
      if (name.value == "") {
        var id = await getSp().getUid();
        name.value = meMemberList
            .firstWhere(
              (element) => element.id == id,
              orElse: () => MemberListObjList().copyWith(
                  id: -1,
                  name: "",
                  sex: 1,
                  iDCardType: "1001",
                  iDCard: "1",
                  phone: "1",
                  image: "",
                  relationship: "4000"),
            )
            .name;
      }

      if (roomInfo.roomId != -1) {
        description.value = '${roomInfo.communityName}${roomInfo.buildingName}'
            '${roomInfo.unitName}${roomInfo.roomName}';
      } else {
        description.value = "未绑定房屋";
      }
      _meConnect.checkRoomNewMsg().then((value) {
        hasNewMsg.value = value;
      });
    }
  }

  Future performClickMyHouse() async {
    await Get.to(() => const MyHouse(),
        arguments: hasNewMsg.value ? ArgumentKey.hasNewMsg : "");
    _meConnect.checkRoomNewMsg().then((value) {
      hasNewMsg.value = value;
    });
  }

  void buildSettingPage() {
    Get.to(() => const Setting());
  }

  void buildFamilyMember() {
    Get.to(() => const FamilyMember())?.whenComplete(() => loadSpData());
  }
}
